/*
   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_log.h"

#include "driver/ledc.h"
#include "soc/gpio_struct.h"

#include "feather_esp.h"

#ifdef USE_MOT
int mot_duty[4] = {0};
int mot_sata[4] = {0};

ledc_channel_config_t mot_channel[MOT_NUM] = 
{
    {
        .channel    = MOT_HS_CH1_CHANNEL,
        .duty       = 0,
        .gpio_num   = MOT_HS_CH1_GPIO,
        .speed_mode = MOT_HS_MODE,
        .timer_sel  = MOT12_HS_TIMER
    },
    {
        .channel    = MOT_HS_CH2_CHANNEL,
        .duty       = 0,
        .gpio_num   = MOT_HS_CH2_GPIO,
        .speed_mode = MOT_HS_MODE,
        .timer_sel  = MOT12_HS_TIMER
    },
    {
        .channel    = MOT_HS_CH3_CHANNEL,
        .duty       = 0,
        .gpio_num   = MOT_HS_CH3_GPIO,
        .speed_mode = MOT_HS_MODE,
        .timer_sel  = MOT34_HS_TIMER
    },
    {
        .channel    = MOT_HS_CH4_CHANNEL,
        .duty       = 0,
        .gpio_num   = MOT_HS_CH4_GPIO,
        .speed_mode = MOT_HS_MODE,
        .timer_sel  = MOT34_HS_TIMER
    },
};

void mot_init(void)
{
    uint8_t ch = 0;
    /*
     * Prepare and set configuration of timers
     * that will be used by LED Controller
     */
    ledc_timer_config_t mot_timer = 
    {
        .duty_resolution = LEDC_TIMER_12_BIT, // resolution of PWM duty
        .freq_hz = 10000,                     // frequency of PWM signal
        .speed_mode = LEDC_HIGH_SPEED_MODE,   // timer mode
        .timer_num = MOT12_HS_TIMER           // timer index
    };
    // Set configuration of timer0 for high speed channels
    ledc_timer_config(&mot_timer);
    mot_timer.timer_num = MOT34_HS_TIMER; 
    ledc_timer_config(&mot_timer);

    for (ch = 0; ch < MOT_NUM; ch++) 
    {
        ledc_channel_config(&mot_channel[ch]);
    }

    ledc_fade_func_install(0);
}

void mot_task(void *pvParameter)
{
    uint8_t ch = 0;
    mot_init();
    while(1) 
    {
        for (ch = 0; ch < MOT_NUM; ch++) 
        {
            if(mot_sata[ch])
            {
                ledc_set_duty(mot_channel[ch].speed_mode, mot_channel[ch].channel, mot_duty[ch]);
                ledc_update_duty(mot_channel[ch].speed_mode, mot_channel[ch].channel);
                mot_sata[ch] = 0;
            }
        }
        vTaskDelay(100 / portTICK_PERIOD_MS);
    }
}
#endif

